from odoo import models, fields, api, _

class HostelCategory(models.Model):
    _name = 'hostel.category'
    _description = 'Hostel Category'
    _rec_name = 'name'

    name = fields.Char(string="Category Name", required=True)
    active = fields.Boolean(string="Active", default=True)
    description = fields.Text(string="Description")

    parent_id = fields.Many2one('hostel.category', string="Parent Category")
    child_ids = fields.One2many('hostel.category', 'parent_id', string="Child Categories")
    parent_path = fields.Char(index=True)
    product_count = fields.Integer(string="Product Count", compute='_compute_product_count')

    _parent_store = True
    _parent_name = 'parent_id'
    _parent_order = 'name'
    _order = 'name'

    @api.constrains('parent_id')
    def _check_parent_id(self):
        if self._has_cycle():
            raise ValueError(_('You can not create recursive categories.'))

    @api.depends('child_ids')
    def _compute_product_count(self):
        for record in self:
            record.product_count = len(record.child_ids)
    
    def create_new_record(self, parent_category_val):
        """创建新记录的方法，传递预定义的字典参数"""
        # 预定义的字典结构
        predefined_data = {
            'name': parent_category_val.get('name', 'Default Parent Category'),
            'description': parent_category_val.get('description', 'Default description'),
            'child_categories': [
                {
                    'name': 'Child category 1',
                    'description': 'Description for child 1'
                },
                {
                    'name': 'Child category 2', 
                    'description': 'Description for child 2'
                }
            ]
        }
        
        # 创建父级分类
        parent_category = self.create({
            'name': predefined_data['name'],
            'description': predefined_data['description'],
            'active': True
        })
        
        # 创建子级分类
        for child_data in predefined_data['child_categories']:
            self.create({
                'name': child_data['name'],
                'description': child_data['description'],
                'parent_id': parent_category.id,
                'active': True
            })
        
        return parent_category